import React, { useState } from 'react'
import { View } from '@tarojs/components'
import Taro, { useRouter } from '@tarojs/taro'
import { AtInput, AtButton, AtMessage  }  from 'taro-ui'
import { request } from '@/utils'
import './index.less'

const FleetEdit = () => {
  const {params} = useRouter()
  const [licensePlateNumber, setLicensePlateNumber] = useState(params?.licensePlateNumber || '')
  const [account, setAccount] = useState(params?.account || '')
  const [name, setName] = useState(params?.name || '')
  const [pwd, setPwd] = useState('')
  const handleChange = (e, type) => {
    if(type === 1) {
      setLicensePlateNumber(e)
    }
    if(type === 2) {
      setAccount(e)
    }
    if(type === 3) {
      setPwd(e)
    }
    if(type === 4) {
      setName(e)
    }
  }

  const handleSave =async () => {
    if(!licensePlateNumber) {
      Taro.atMessage({ message: '请输入车牌号', type: 'error' })
      return
    }
    if(!account) {
      Taro.atMessage({ message: '请输入账号', type: 'error' })
      return
    }
    if(!pwd) {
      Taro.atMessage({ message: '请输入密码', type: 'error' })
      return
    }
    if(!name) {
      Taro.atMessage({ message: '请输入姓名', type: 'error' })
      return
    }
    if(params.userId) {
      const {error} = await request({ url: 'hkshihua/motorcade/addOrUpdateMyMotocae',header: {"Content-Type": "application/json"},method: 'post', data: JSON.stringify({account,name, licensePlateNumber, pwd, userId: params.userId})})
      if(error) return
    } else {
      const {error} = await request({ url: 'hkshihua/motorcade/addOrUpdateMyMotocae',header: {"Content-Type": "application/json"},method: 'post', data: JSON.stringify({account,name, licensePlateNumber, pwd})})
      if(error) return
    }
    Taro.atMessage({ message: '保存成功', type: 'success'})
    Taro.navigateBack()
  }
  return (
    <View>
      <AtMessage />
       <View className='edit'>
        <AtInput cursor={-1} title='姓名' name='name' type='text' placeholder='请输入姓名' value={name} onChange={(e) => handleChange(e, 4)} />
        <AtInput cursor={-1} title='车牌号' name='licensePlateNumber' type='text' placeholder='请输入车牌号' value={licensePlateNumber} onChange={(e) => handleChange(e, 1)} />
        <AtInput cursor={-1} title='账号' name='account' type='text' placeholder='请输入账号' value={account} onChange={(e) => handleChange(e, 2)} />
        <AtInput  cursor={-1} title='密码' name='pwd' type='password' placeholder='请输入密码' value={pwd} onChange={(e) => handleChange(e, 3)} />
      </View>
     <View className='btn'>
      <AtButton type='primary' full onClick={handleSave}>保存</AtButton>
     </View>
    </View>
  )
}

export default FleetEdit
